// ==UserScript==
// @name         东奥教育自动学习
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  自动点击未学习和学习中的课程进行学习
// @author       DarkSheep
// @match        https://study.dongao.cn/h5/*
// @match        https://acc.jxf.gov.cn/jxgzhh5/*
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // 页面类型判断
    const PAGE_TYPE = {
        STUDY_CENTER: 'studyCenter',
        VIDEO: 'video',
        JX_PLATFORM: 'jxPlatform',
        DONGAO_HOME: 'dongaoHome',
        OTHER: 'other'
    };

    // 获取当前页面类型
    function getPageType() {
        const path = window.location.pathname;
        const hostname = window.location.hostname;
        
        if(hostname === 'acc.jxf.gov.cn') {
            console.log('当前页面: 江西会计平台');
            return PAGE_TYPE.JX_PLATFORM;
        } else if(path === '/h5/home') {
            console.log('当前页面: 东奥首页');
            return PAGE_TYPE.DONGAO_HOME;
        } else if(path === '/h5/studyCenter/study' || path === '/h5/studyCenter/study/') {
            console.log('当前页面: 学习中心');
            return PAGE_TYPE.STUDY_CENTER;
        } else if(path === '/h5/video' || path === '/h5/video/') {
            console.log('当前页面: 视频播放');
            return PAGE_TYPE.VIDEO;
        }
        console.log('当前页面路径:', path);
        return PAGE_TYPE.OTHER;
    }

    // 课程状态统计
    let courseStats = {
        total: 0,
        notStarted: 0,
        inProgress: 0,
        completed: 0,
        abnormal: 0,
        currentCourse: null
    };

    let isLearning = false;
    let controlPanel = null;

    // 添加自动学习设置
    let autoLearnEnabled = true; // 默认开启自动学习

    // 添加控制面板
    function addControlPanel() {
        // 如果已存在控制面板则移除
        if(controlPanel) {
            controlPanel.remove();
        }

        controlPanel = document.createElement('div');
        // 修改样式，确保面板显示在最上层
        controlPanel.style.cssText = `
            position: fixed;
            top: 80px;
            right: 20px;
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 15px;
            border-radius: 8px;
            z-index: 999999;
            min-width: 200px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            font-size: 14px;
            line-height: 1.5;
        `;
        
        // 根据页面类型显示不同内容
        if(getPageType() === PAGE_TYPE.STUDY_CENTER) {
            controlPanel.innerHTML = `
                <div style="margin-bottom: 10px; font-weight: bold; font-size: 16px;">学习控制面板</div>
                <div>课程总数: <span id="total-courses">0</span></div>
                <div>未学习: <span id="not-started">0</span></div>
                <div>学习中: <span id="in-progress">0</span></div>
                <div>已完成: <span id="completed">0</span></div>
                <div>听课异常: <span id="abnormal">0</span></div>
                <div>当前课程: <span id="current-course">无</span></div>
                <div style="margin: 10px 0; padding: 5px 0; border-top: 1px solid rgba(255,255,255,0.2);">
                    <label style="cursor: pointer; display: flex; align-items: center;">
                        <input type="checkbox" id="auto-learn-checkbox" ${autoLearnEnabled ? 'checked' : ''} 
                               style="margin-right: 5px;">
                        <span>自动学习</span>
                    </label>
                </div>
                <div style="display: flex; gap: 10px;">
                    <button id="start-learn" style="
                        padding: 5px 15px;
                        border: none;
                        border-radius: 4px;
                        background: #4CAF50;
                        color: white;
                        cursor: pointer;
                    ">开始学习</button>
                    <button id="stop-learn" style="
                        padding: 5px 15px;
                        border: none;
                        border-radius: 4px;
                        background: #f44336;
                        color: white;
                        cursor: pointer;
                    ">停止学习</button>
                </div>
            `;
        } else if(getPageType() === PAGE_TYPE.VIDEO) {
            controlPanel.innerHTML = `
                <div style="margin-bottom: 10px; font-weight: bold; font-size: 16px;">视频控制面板</div>
                <div>本页视频数量: <span id="video-count">0</span></div>
                <div>当前课程: <span id="current-course">${courseStats.currentCourse || '无'}</span></div>
                <div>正在学习: <span id="current-playing">无</span></div>
                <button id="back-to-list" style="
                    margin-top: 10px;
                    padding: 5px 15px;
                    border: none;
                    border-radius: 4px;
                    background: #2196F3;
                    color: white;
                    cursor: pointer;
                ">返回列表</button>
            `;

            // 添加一个延时来获取和更新视频信息
            setTimeout(() => {
                // 获取所有视频标题
                const allVideos = document.querySelectorAll('p.title.two-line[data-v-6f134c9c]');
                const videoCount = document.getElementById('video-count');
                if (videoCount) {
                    videoCount.textContent = allVideos.length;
                }

                // 获取当前正在播放的视频
                const playingVideo = document.querySelector('.play.play-pause.play-on p.title.two-line[data-v-6f134c9c]');
                const currentPlaying = document.getElementById('current-playing');
                if (currentPlaying && playingVideo) {
                    currentPlaying.textContent = playingVideo.textContent.trim();
                }
            }, 1000);
        } else if(getPageType() === PAGE_TYPE.JX_PLATFORM) {
            controlPanel.innerHTML = `
                <div style="margin-bottom: 10px; font-weight: bold; font-size: 16px;">江西会计平台控制面板</div>
                <div>未通过课程数: <span id="failed-courses">0</span></div>
                <div>自动学习: 
                    <label style="cursor: pointer;">
                        <input type="checkbox" id="auto-learn-checkbox" ${autoLearnEnabled ? 'checked' : ''}>
                        启用
                    </label>
                </div>
            `;

            // 定期统计未通过课程数量并自动点击去学习
            const updateInterval = setInterval(() => {
                // 统计未通过课程数
                const failedCourses = document.querySelectorAll('div.btn.failed.fl[data-v-60b8186e]');
                const failedCount = document.getElementById('failed-courses');
                if(failedCount) {
                    failedCount.textContent = failedCourses.length;
                }

                // 如果启用了自动学习，首先点击"未通过"的文本，再点击去学习按钮，精确到"去学习"按钮
                if(autoLearnEnabled) {
                    // 精确匹配文本为"未通过"的文本
                    const failedText = document.querySelector('div.btn.failed.fl[data-v-60b8186e]');
                    if(failedText) {
                        console.log('找到未通过文本，准备点击');
                        failedText.click();
                    }

                    // 精确匹配文本为"去学习"的蓝色按钮
                    const buttons = document.querySelectorAll('div.btn.blue[data-v-60b8186e]');
                    buttons.forEach(button => {
                        if(button.textContent.trim() === '去学习') {
                            console.log('找到去学习按钮，准备点击');
                            button.click();
                        }
                    });
                }
            }, 5000);

            // 绑定自动学习复选框事件
            setTimeout(() => {
                const checkbox = document.getElementById('auto-learn-checkbox');
                if(checkbox) {
                    checkbox.addEventListener('change', (e) => {
                        autoLearnEnabled = e.target.checked;
                        localStorage.setItem('dongao_auto_learn', autoLearnEnabled);
                        console.log('自动学习设置已更新:', autoLearnEnabled);
                    });
                }
            }, 100);
        }

        // 确保添加到body的最后
        document.body.appendChild(controlPanel);
        console.log('控制面板已添加到页面');

        // 使用setTimeout确保DOM元素已经加载
        setTimeout(() => {
            try {
                // 绑定按钮事件
                if(getPageType() === PAGE_TYPE.STUDY_CENTER) {
                    const autoLearnCheckbox = document.getElementById('auto-learn-checkbox');
                    const startButton = document.getElementById('start-learn');
                    const stopButton = document.getElementById('stop-learn');

                    if(autoLearnCheckbox) {
                        autoLearnCheckbox.addEventListener('change', (e) => {
                            autoLearnEnabled = e.target.checked;
                            localStorage.setItem('dongao_auto_learn', autoLearnEnabled);
                            console.log('自动学习设置已更新:', autoLearnEnabled);
                        });
                    }

                    if(startButton) {
                        startButton.addEventListener('click', startAutoLearn);
                    }

                    if(stopButton) {
                        stopButton.addEventListener('click', stopAutoLearn);
                    }
                } else if(getPageType() === PAGE_TYPE.VIDEO) {
                    const backButton = document.getElementById('back-to-list');
                    if(backButton) {
                        backButton.addEventListener('click', () => {
                            window.history.back();
                        });
                    }
                } else if(getPageType() === PAGE_TYPE.JX_PLATFORM) {
                    const checkbox = document.getElementById('auto-learn-checkbox');
                    if(checkbox) {
                        checkbox.addEventListener('change', (e) => {
                            autoLearnEnabled = e.target.checked;
                            localStorage.setItem('dongao_auto_learn', autoLearnEnabled);
                            console.log('自动学习设置已更新:', autoLearnEnabled);
                        });
                    }
                }
                console.log('事件绑定完成');
            } catch(error) {
                console.error('绑定事件时出错:', error);
            }
        }, 100);
    }

    // 更新统计数据显示
    function updateStats() {
        try {
            const elements = {
                'total-courses': courseStats.total,
                'not-started': courseStats.notStarted,
                'in-progress': courseStats.inProgress,
                'completed': courseStats.completed,
                'abnormal': courseStats.abnormal,
                'current-course': courseStats.currentCourse || '无'
            };

            for(const [id, value] of Object.entries(elements)) {
                const element = document.getElementById(id);
                if(element) {
                    element.textContent = value;
                }
            }
        } catch(error) {
            console.error('更新统计数据时出错:', error);
        }
    }

    // 统计课程状态
    function analyzeCourses() {
        // 重置统计数据
        courseStats = {
            total: 0,
            notStarted: 0,
            inProgress: 0,
            completed: 0,
            abnormal: 0,
            currentCourse: null
        };

        // 获取所有课程列表
        const courseItems = document.querySelectorAll('.swiper-slide li .item');
        courseStats.total = courseItems.length;

        courseItems.forEach(item => {
            // 根据课程状态的class来判断
            const statusElement = item.querySelector('.course-tab');
            if(!statusElement) return;
            
            // 根据class判断状态
            if(statusElement.classList.contains('blue')) {
                courseStats.inProgress++; // 学习中
            } else if(statusElement.classList.contains('blue2')) {
                courseStats.completed++; // 已完成
            } else if(statusElement.classList.contains('red')) {
                courseStats.abnormal++; // 听课异常
            } else {
                courseStats.notStarted++; // 未学习
            }
        });

        updateStats();
    }

    // 获取下一个要学习的课程
    function getNextCourse() {
        // 优先获取学习中的课程
        let nextCourse = document.querySelector('.swiper-slide li .item:has(.course-tab.blue)');
        
        // 如果没有学习中的课程，则获取未学习的课程
        if(!nextCourse) {
            nextCourse = document.querySelector('.swiper-slide li .item:not(:has(.course-tab.blue)):not(:has(.course-tab.blue2)):not(:has(.course-tab.red))');
        }

        return nextCourse;
    }

    // 停止自动学习
    function stopAutoLearn() {
        isLearning = false;
        document.getElementById('start-learn').disabled = false;
    }

    // 检查学习进度是否完成
    function isLearningCompleted() {
        // 检查进度100%
        const progressElement = document.querySelector('.progress-icon span');
        if(progressElement && progressElement.textContent.trim() === '100%') {
            console.log('检测到听课进度100%');
            return true;
        }
        return false;
    }

    // 修改视频播放控制逻辑
    async function handleVideoPlay() {
        // 等待视频元素加载
        const videoElement = await waitForElement('#player_daPlayer');
        if(!videoElement) return;
        
        // 获取并更新当前课程标题
        const titleElement = await waitForElement('.course-title-tit');
        if(titleElement) {
            courseStats.currentCourse = titleElement.textContent.trim();
            const currentCourseElement = document.getElementById('current-course');
            if(currentCourseElement) {
                currentCourseElement.textContent = courseStats.currentCourse;
            }
        }
        
        return new Promise((resolve) => {
            let completedCount = 0; // 记录连续检测到完成的次数
            
            // 定期检查学习进度
            const progressCheckInterval = setInterval(() => {
                if(isLearningCompleted()) {
                    completedCount++;
                    console.log(`检测到听课进度100% (${completedCount}/3)`);
                    
                    // 连续3次检测到完成才返回
                    if(completedCount >= 3) {
                        clearInterval(progressCheckInterval);
                        clearInterval(checkVideoStatus);
                        console.log('听课进度确认完成，准备返回');
                        setTimeout(() => {
                            const backButton = document.getElementById('back-to-list');
                            if(backButton) {
                                console.log('自动点击返回按钮');
                                backButton.click();
                            } else {
                                console.log('未找到返回按钮，使用history.back()');
                                window.history.back();
                            }
                            resolve();
                        }, 5000);
                    }
                } else {
                    // 如果检测到未完成，重置计数
                    if(completedCount > 0) {
                        console.log('听课进度未达到100%，重置计数');
                        completedCount = 0;
                    }
                }
            }, 10000); // 每10秒检查一次

            // 监听视频状态
            const checkVideoStatus = setInterval(() => {
                const playerContainer = document.querySelector('#player');
                if(playerContainer) {
                    // 检查是否暂停状态
                    if(playerContainer.classList.contains('vjs-paused')) {
                        console.log('检测到视频暂停，尝试恢复播放');
                        const playButton = document.querySelector('.vjs-play-control');
                        if(playButton) {
                            playButton.click();
                        }
                    }
                }
            }, 1000);

            // 添加定期更新当前播放视频的逻辑
            const updatePlayingVideo = setInterval(() => {
                const playingVideo = document.querySelector('.play.play-pause.play-on p.title.two-line[data-v-6f134c9c]');
                const currentPlaying = document.getElementById('current-playing');
                if (currentPlaying && playingVideo) {
                    currentPlaying.textContent = playingVideo.textContent.trim();
                }
            }, 2000);

            // 移除最大等待时间限制，只有在听课进度达到100%时才返回
        });
    }

    // 等待元素加载的工具函数
    function waitForElement(selector, timeout = 5000) {
        return new Promise((resolve) => {
            if(document.querySelector(selector)) {
                return resolve(document.querySelector(selector));
            }
            
            const observer = new MutationObserver(() => {
                if(document.querySelector(selector)) {
                    observer.disconnect();
                    resolve(document.querySelector(selector));
                }
            });
            
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
            
            // 设置超时
            setTimeout(() => {
                observer.disconnect();
                resolve(null);
            }, timeout);
        });
    }

    // 开始自动学习
    async function startAutoLearn() {
        if(isLearning || getPageType() !== PAGE_TYPE.STUDY_CENTER) return;
        
        isLearning = true;
        document.getElementById('start-learn').disabled = true;

        while(isLearning) {
            // 确保在学习中心页面
            if(getPageType() !== PAGE_TYPE.STUDY_CENTER) {
                await new Promise(resolve => setTimeout(resolve, 1000));
                continue;
            }

            analyzeCourses();
            
            const nextCourse = getNextCourse();
            if(!nextCourse) {
                alert('没有需要学习的课程了！');
                stopAutoLearn();
                return;
            }

            // 获取课程名称
            const courseName = nextCourse.querySelector('.title')?.textContent.trim();
            courseStats.currentCourse = courseName;
            updateStats();

            // 点击课程
            nextCourse.click();

            // 等待页面跳转到视频页面
            await new Promise(resolve => setTimeout(resolve, 3000));
            
            // 确认已进入视频页面
            if(getPageType() === PAGE_TYPE.VIDEO) {
                try {
                    // 处理视频播放，等待播放完成
                    await handleVideoPlay();
                    
                    // 视频播放完成后等待2秒再返回
                    await new Promise(resolve => setTimeout(resolve, 2000));
                    
                    // 返回课程列表
                    window.history.back();
                } catch(error) {
                    console.error('视频播放出错:', error);
                    // 出错时也返回列表
                    window.history.back();
                }
            }
            
            // 等待页面加载
            await new Promise(resolve => setTimeout(resolve, 2000));
        }
    }

    // 页面加载和切换处理
    function initializePage() {
        const pageType = getPageType();
        console.log('初始化页面类型:', pageType);
        
        if(pageType === PAGE_TYPE.DONGAO_HOME) {
            console.log('检测到东奥首页，准备自动跳转到学习中心...');
            // 设置定时器，每5秒尝试跳转一次
            const redirectInterval = setInterval(() => {
                console.log('尝试跳转到学习中心...');
                window.location.href = 'https://study.dongao.cn/h5/studyCenter/study';
            }, 5000);

            // 添加一个简单的控制面板显示状态
            controlPanel = document.createElement('div');
            controlPanel.style.cssText = `
                position: fixed;
                top: 80px;
                right: 20px;
                background: rgba(0,0,0,0.8);
                color: white;
                padding: 15px;
                border-radius: 8px;
                z-index: 999999;
            `;
            controlPanel.innerHTML = `
                <div>当前页面: 东奥首页</div>
                <div>状态: 即将跳转到学习中心...</div>
            `;
            document.body.appendChild(controlPanel);
        } else if(pageType === PAGE_TYPE.STUDY_CENTER) {
            console.log('开始初始化学习中心页面...');
            // 从localStorage读取自动学习设置
            const savedAutoLearn = localStorage.getItem('dongao_auto_learn');
            if(savedAutoLearn !== null) {
                autoLearnEnabled = savedAutoLearn === 'true';
            }

            const initInterval = setInterval(() => {
                const courseList = document.querySelector('.swiper-slide li .item');
                if(courseList) {
                    console.log('检测到课程列表，添加控制面板');
                    clearInterval(initInterval);
                    addControlPanel();
                    analyzeCourses();

                    // 如果启用了自动学习，等待5秒后自动开始
                    if(autoLearnEnabled) {
                        console.log('自动学习已启用，5秒后开始学习');
                        setTimeout(() => {
                            const startButton = document.getElementById('start-learn');
                            if(startButton && !isLearning) {
                                console.log('自动开始学习...');
                                startButton.click();
                            }
                        }, 5000);
                    }
                } else {
                    console.log('等待课程列表加载...');
                }
            }, 1000);
        } else if(pageType === PAGE_TYPE.VIDEO) {
            console.log('初始化视频页面...');
            addControlPanel();
            handleVideoPlay();
        } else if(pageType === PAGE_TYPE.JX_PLATFORM) {
            console.log('初始化江西会计平台页面...');
            addControlPanel();
        } else {
            console.log('其他页面，不进行初始化');
        }
    }

    // 修改页面变化监听部分
    let lastUrl = location.href;
    new MutationObserver(() => {
        const url = location.href;
        if (url !== lastUrl) {
            console.log('检测到页面变化:', url);
            lastUrl = url;
            
            // 如果是返回学习中心且自动学习已启用，则继续学习
            if(getPageType() === PAGE_TYPE.STUDY_CENTER && isLearning && autoLearnEnabled) {
                console.log('返回学习中心，继续自动学习');
                // 等待页面加载完成
                setTimeout(async () => {
                    try {
                        // 等待控制面板加载完成
                        await waitForElement('#total-courses');
                        
                        // 重新分析课程状态
                        analyzeCourses();
                        
                        // 获取下一个课程
                        const nextCourse = getNextCourse();
                        if(nextCourse) {
                            // 获取课程名称
                            const titleElement = nextCourse.querySelector('.title');
                            if(titleElement) {
                                const courseName = titleElement.textContent.trim();
                                courseStats.currentCourse = courseName;
                                updateStats();

                                console.log('自动开始下一个课程:', courseName);
                                // 点击课程
                                nextCourse.click();
                            } else {
                                console.error('未找到课程标题元素');
                            }
                        } else {
                            console.log('没有更多需要学习的课程');
                            stopAutoLearn();
                        }
                    } catch(error) {
                        console.error('继续学习时出错:', error);
                    }
                }, 2000); // 等待2秒确保页面加载完成
            } else {
                initializePage();
            }
        }
    }).observe(document, {subtree: true, childList: true});

    // 初始化时也输出日志
    console.log('脚本开始运行，当前URL:', location.href);
    initializePage();

})(); 